package com.haruhinav.Utils;

import com.haruhinav.entity.EmailDetails;
import com.haruhinav.entity.YiBanRemindPunch;
import com.haruhinav.mapper.YiBanRemindPunchMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MailUtils {

    @Autowired
    JavaMailSenderImpl javaMailSender;

    @Autowired
    YiBanRemindPunchMapper remindPunchMapper;

    /**
     * 自动发送邮箱
     * 易班打卡提示服务
     * 异步类
     */
    @Async
    @Scheduled(cron = "0 30 10 * * ?") //每天10点30分
    public void autoRemindToPunchIn(){

        YiBanRemindPunch yiBanRemindPunch = new YiBanRemindPunch();
        yiBanRemindPunch.setIsOpen(1);//查询条件 查询出打开提示的所有用户
        List<YiBanRemindPunch> list = remindPunchMapper.queryYiBanRemindPunch(yiBanRemindPunch);
        if(null != list && list.size()>0){
            EmailDetails emailDetails = remindPunchMapper.getEmailDetails();
//        由于setTo() 需要一个string数组而不是集合
//        将集合里的邮箱填入数组
            String[] emails = new String[list.size()];
            for (int i = 0,len = emails.length;i < len;i++){
                emails[i] = list.get(i).getEmail();
            }

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(emailDetails.getSubject());
            mailMessage.setText(emailDetails.getText());
            mailMessage.setTo(emails);
            mailMessage.setFrom(Constants.SENDER);
            javaMailSender.send(mailMessage);
        }
    }

    /**
     * 自定义发送 简单邮件
     * @param subject
     * @param text
     * @param to
     */
    @Async //标注为异步类
    public void sendCustomSimpleMail(String subject,String text,String... to){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        mailMessage.setTo(to);
        mailMessage.setFrom(Constants.SENDER);
        javaMailSender.send(mailMessage);
    }

//    由于外部设置附件功能目前不知道如何实现，所有暂时不做自定义发送复杂邮件
}
